/**
 * 首页服务层
 */
const activityDao = require('../dao/activityDao');
const systemDao = require('../dao/systemDao');
const { validatePagination } = require('../utils/validation');

/**
 * 获取轮播图服务
 * @returns {Array} 轮播图列表
 */
const getBanners = async () => {
  const banners = await activityDao.getActiveBanners();
  
  return banners.map(banner => ({
    id: banner.id,
    title: banner.title,
    description: banner.description,
    image: banner.image,
    link: banner.link,
    sort: banner.sort,
    status: banner.status
  }));
};

/**
 * 获取功能模块服务
 * @returns {Array} 功能模块列表
 */
const getFunctionModules = async () => {
  const modules = await systemDao.getFunctionModules({ enabled: true });
  
  return modules.map(module => ({
    key: module.key,
    name: module.name,
    icon: module.icon,
    bgColor: module.bg_color,
    iconColor: module.icon_color,
    route: module.route,
    sort: module.sort,
    enabled: module.enabled
  }));
};

/**
 * 获取推荐内容服务
 * @param {Object} query - 查询参数
 * @param {number} userId - 用户ID（可选）
 * @returns {Object} 推荐内容分页结果
 */
const getRecommendations = async (query, userId = null) => {
  const { page, limit } = validatePagination(query);
  
  const result = await systemDao.getRecommendations({
    page,
    limit,
    is_active: true
  });

  const formattedList = result.recommendations.map(item => ({
    id: item.id,
    title: item.title,
    description: item.description,
    cover: item.cover,
    rating: parseFloat(item.rating || 0),
    studyCount: item.view_count || 0,
    type: item.type,
    duration: item.duration || 0,
    difficulty: item.difficulty,
    category: item.courseCategory ? {
      id: item.courseCategory.id,
      name: item.courseCategory.name
    } : null,
    tags: item.tags || [],
    createdAt: item.created_at
  }));

  return {
    list: formattedList,
    total: result.total,
    page,
    limit
  };
};

/**
 * 获取活动列表服务
 * @returns {Array} 活动列表
 */
const getActivities = async () => {
  const activities = await activityDao.getActiveActivities();
  
  return activities.map(activity => ({
    id: activity.id,
    title: activity.title,
    description: activity.description,
    poster: activity.poster,
    startTime: activity.start_time,
    endTime: activity.end_time,
    status: activity.status,
    participantCount: activity.participant_count || 0,
    maxParticipants: activity.max_participants,
    tags: activity.tags || [],
    createdAt: activity.created_at
  }));
};

/**
 * 记录推荐内容查看次数服务
 * @param {number} recommendationId - 推荐内容ID
 * @param {number} userId - 用户ID（可选）
 * @returns {boolean} 记录结果
 */
const recordRecommendationView = async (recommendationId, userId = null) => {
  if (!recommendationId) {
    throw new Error('推荐内容ID不能为空');
  }

  // 检查推荐内容是否存在
  const recommendation = await systemDao.getRecommendationById(recommendationId);
  if (!recommendation) {
    throw new Error('推荐内容不存在');
  }

  // 增加查看次数
  await systemDao.incrementRecommendationViewCount(recommendationId);

  // 如果有用户ID，可以记录用户查看历史
  if (userId) {
    await systemDao.recordUserViewHistory(userId, recommendationId, 'recommendation');
  }

  return true;
};

/**
 * 获取首页统计数据服务
 * @param {number} userId - 用户ID（可选）
 * @returns {Object} 统计数据
 */
const getHomeStats = async (userId = null) => {
  const stats = {
    totalUsers: await systemDao.getTotalUserCount(),
    totalCourses: await systemDao.getTotalCourseCount(),
    totalStudyTime: await systemDao.getTotalStudyTime(),
    activeUsers: await systemDao.getActiveUserCount()
  };

  // 如果有用户ID，添加个人统计
  if (userId) {
    const userStats = await systemDao.getUserStats(userId);
    stats.userStats = {
      studyTime: userStats.total_study_time || 0,
      practiceCount: userStats.practice_count || 0,
      level: userStats.level || 1,
      experience: userStats.experience || 0,
      streak: userStats.streak || 0
    };
  }

  return stats;
};

/**
 * 搜索推荐内容服务
 * @param {Object} searchParams - 搜索参数
 * @returns {Object} 搜索结果
 */
const searchRecommendations = async (searchParams) => {
  const { keyword, type, difficulty, category, page, limit } = searchParams;
  const { page: validPage, limit: validLimit } = validatePagination({ page, limit });

  const searchOptions = {
    keyword,
    type,
    difficulty,
    category,
    page: validPage,
    limit: validLimit,
    is_active: true
  };

  const result = await systemDao.searchRecommendations(searchOptions);

  const formattedList = result.recommendations.map(item => ({
    id: item.id,
    title: item.title,
    description: item.description,
    cover: item.cover,
    rating: parseFloat(item.rating || 0),
    studyCount: item.view_count || 0,
    type: item.type,
    duration: item.duration || 0,
    difficulty: item.difficulty,
    category: item.category ? {
      id: item.category.id,
      name: item.category.name
    } : null,
    tags: item.tags || [],
    createdAt: item.created_at
  }));

  return {
    list: formattedList,
    total: result.total,
    page: validPage,
    limit: validLimit
  };
};

module.exports = {
  getBanners,
  getFunctionModules,
  getRecommendations,
  getActivities,
  recordRecommendationView,
  getHomeStats,
  searchRecommendations
};
